package com.schoolai.tts.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.schoolai.tts.service.CosyVoiceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Copyright(C),2019-2025，XX公司
 * FileName:CosyVoiceServiceImpl
 * Author:
 * 创建时间：2025/9/30 14:13
 * Description:
 * History:
 * <auth>        <time>       <version>       <desc>
 * 作者          修改时间       版本号         描述
 */
@Slf4j
@Service
public class CosyVoiceServiceImpl implements CosyVoiceService {
    //模型名称 龙飞
    private static String model = "cosyvoice-v1";
    //音色名称
    private static String voice = "longfei";

    @Autowired
    private SpeechSynthesisModel synthesisModel;

    public void genVoiceFile(String text) {
        DashScopeSpeechSynthesisOptions scopeSpeechSynthesisOptions = DashScopeSpeechSynthesisOptions.builder()
                .withModel(model)
                .withVoice(voice)
                .build();
        ByteBuffer byteBuffer = synthesisModel.call(
                        new SpeechSynthesisPrompt(text,
                                scopeSpeechSynthesisOptions))
                .getResult()
                .getOutput()
                .getAudio();
        byte[] bytes = byteBuffer.array();
        File file = new File("D:\\audio\\" + UUID.randomUUID().toString(Boolean.TRUE) + ".mp3");
        if (!file.getParentFile().exists()){
            FileUtil.mkParentDirs(file);
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            log.info("创建成功：{}", file.getAbsoluteFile());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
